import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列实现生产者，消费者
 * 0：共享变量
 * 1：判断
 * 2：干活
 * 3：通知
 */
public class QueueProConDemo {

    private static volatile boolean proFlag = true;
    private static BlockingQueue<Integer> synchronousQueue;


    private static void product() {

        try {
            while (proFlag){
                boolean offer = synchronousQueue.offer(1, 2L, TimeUnit.SECONDS);
                System.out.println(offer);
                if(offer){
                    System.out.println(Thread.currentThread().getName()+"生产完成");
                }else {
                    System.out.println(Thread.currentThread().getName()+"生产失败");
                }
            }
        } catch (Exception e) {
        }

    }

    private static void consumer() {
        try {
            while (proFlag){
                Integer poll = synchronousQueue.poll(2L, TimeUnit.SECONDS);
                if(null != poll && poll == 1 ){
                    System.out.println(Thread.currentThread().getName()+"消费完成");
                }else {
                    System.out.println(Thread.currentThread().getName()+"消费失败");
                }
            }
        } catch (Exception e) {
        }
    }

    private static void stop(){
        proFlag = false;
        synchronousQueue.clear();
    }

    /**
     * 多个生产者，消费者存在问题?
     * TODO
     * @param args
     */
    public static void main(String[] args) {
        synchronousQueue = new ArrayBlockingQueue<>(3);
        new Thread(()->{
            product();
        },"aa").start();
        new Thread(()->{
            product();
        },"cc").start();

        new Thread(()->{
            consumer();
        },"dd").start();

        new Thread(()->{
            consumer();
        },"bb").start();
        stop();
    }


}
